<template>
    <div class="app-container">
        <!-- <el-steps :active="ferState" align-center>
          <el-step title="开始" description=""></el-step>
          <el-step title="关键工序申请" description=""></el-step>
          <el-step title="关键工序培训" description=""></el-step>
          <el-step title="考核" description=""></el-step>
          <el-step title="岗位案例培训" description=""></el-step>
          <el-step title="考核" description=""></el-step>   
          <el-step title="岗位实操培训" description=""></el-step>   
          <el-step title="考核" description=""></el-step>   
          <el-step title="颁发上岗证" description=""></el-step>
          <el-step title="回写MES信息" description=""></el-step>
          <el-step title="结束" description=""></el-step>
        </el-steps> -->
        <div style="margin: 5px 0 5px 50px;display: flex;">
            <el-link style="font-size: 20px;margin-right: 10px;" :underline="false" target="_blank">基础信息</el-link>
            <!-- <el-button type="primary">批量导入</el-button>   -->
            <el-upload
            class="upload-demo"
            ref="upload"
            :action="action"
            :on-success="handleSuccess"
            :file-list="fileList"
            :headers="httpHeader"   
            :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">批量导入</el-button>
              <div style="display: inline;">
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                <!-- <el-button type="primary" @click="addTrain">添加培训人</el-button>  -->
              </div>
            </el-upload>
        </div>  
        <div>
            <el-form :inline="true" :model="createForm"  :rules="rules" ref="createForm">
                <div style="display: flex; ">
                    <el-form-item label="姓名" prop="userName" label-width="100px">
                        <el-input disabled v-model="createForm.userName" autosize  style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="工号" prop="jobNumber" label-width="100px" >
                        <el-input disabled v-model="createForm.jobNumber" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="部门" prop="workCenter" label-width="100px" >
                        <el-input disabled v-model="createForm.workCenter" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="岗位类别" prop="jobCategory" label-width="100px" >
                        <el-input disabled v-model="createForm.jobCategory" autosize style="width: 120px"/>
                    </el-form-item>
                    <el-form-item label="岗位名称" prop="jobTitle" label-width="120px" >
                        <el-input disabled v-model="createForm.jobTitle" autosize style="width: 120px"/>
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="岗位级别" prop="rankOfPosition" label-width="100px" >
                        <el-select 
                             v-model="createForm.rankOfPosition" 
                             clearable      
                             filterable
                             disabled
                             style="width: 120px"
                             class="ul-item">
                             <el-option :value="item" :label="item" v-for="(item,index) in this.centerList" :key="index"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="直接主管" prop="parentName" label-width="100px" >
                        <el-select disabled v-model="createForm.parentName"    placeholder="" @focus="getjobTitle" style="width:120px" @change="changeJobTitle">
                            <el-option :value="item.id" :label="item.jobTitle" v-for="(item,index) in this.jobTitleList" :key="index"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="培训类别" prop="trainingCategory" label-width="100px">
                        <el-select disabled style="width: 120px;" clearable filterable v-model="createForm.trainingCategory" placeholder="" @change="changeName1" @focus="getuserList(0)" class="ul-item">
                            <el-option :value="item.userName" :label="item.userName" v-for="(item,index) in this.userList" :key="index"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="入职时间" prop="entryTime" label-width="100px" >
                        <el-select clearable filterable disabled @change="createForm.nowJobTitle = ''" v-model="createForm.entryTime" placeholder="" style="width:170px">
                          <el-option :value="item" :label="item" v-for="(item,index) in this.jobCategoryList" :key="index"/>
                        </el-select>
                    </el-form-item>     
                </div>
            </el-form>
            <div style="display:flex;justify-content:space-between">
                <!-- pagination 分页 -->
                <div style="display: flex; justify-content: center; padding: 10px 0">
                  <span style="line-height: 28px; font-size: 13px"
                    >本次培训共 {{ total }} 人 </span>
                  <el-pagination
                    background
                    @current-change="handleCurrentChange"
                    :current-page="currentPage1"
                    :page-size="1"
                    layout="prev, pager, next"
                    small
                    :total="total"
                  >
                  </el-pagination>
                </div>
                <div  v-if="createForm" style="margin-right: 460px;">
                    <span style="margin-right: 20px">处理人：{{createForm.updateUserName  }}</span>
                    <span>处理时间：{{createForm.updateTime ? createForm.updateTime:createForm.createTime}}</span>
                </div>
            </div>
        </div>
        <div>
            <div style="margin: 5px 0 5px 50px; display: flex; justify-content:space-between">
                <div>
                    <el-link style="font-size: 20px;margin-right: 10px;" :underline="false" target="_blank">岗位案例培训</el-link>
                    <el-button :disabled="boolGWAL" type="primary" @click="trainingClick">培训计划维护</el-button>      
                    <!-- <el-button type="primary" @click="trainingClick">培训计划维护</el-button>       -->
                </div>
                <el-button :disabled="ferState != 3" style="margin-right: 200px;" type="success"  size="medium" @click="skipTrain">完成培训</el-button>
            </div>
            <el-table :data="tableInfo" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
                <el-table-column  label="序号" type="index" align="center" width="80px"/>
                <el-table-column label="培训内容"  prop="trainingContent" align="center"/>
                <el-table-column label="内容类别"  prop="contentType" align="center"/>
                <el-table-column label="培训讲师"  prop="userName" align="center"/>
                <el-table-column label="培训时间"  prop="trainingTime" align="center"/>
                <el-table-column label="考核方式"  prop="evaluationMode" align="center"/>
                <el-table-column label="培训记录"  prop="trainingPhoto" align="center"/>
                <el-table-column label="考核记录"  prop="assessmentData" align="center"/>
                <el-table-column label="效果评价"  prop="effectivenessEvaluation" align="center"/>
                <el-table-column label="培训结果"  prop="evaluationResult" align="center"/>
            </el-table> 
            <div v-if="tableInfo.length" style="display:flex;justify-content:space-between">
                <div></div>
                <div style="margin-right: 460px;">
                    <span style="margin-right: 20px">处理人：{{tableInfo[0].updateUserName }}</span>
                    <span>处理时间：{{tableInfo[0].updateTime ? tableInfo[0].updateTime:tableInfo[0].createTime}}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { transferSave,knowledgeFind,programFind,transferGet,recordSaveList,recordSave,userKnowledgeRecordState,recordFind,word04 } from "@/api/knowledgeSkill"
import { searchWorkers } from '@/api/chargingData'
import { modifyWorkers } from '@/api/user'
import { findZplPrinterInfoList } from '../../api/orderAndMachine'
import {uploadURL} from '@/utils/baseURL'
import mixin from '@/utils/mixin.js'
import { set } from 'vue'
export default {
    name: 'promotedManagement',
    mixins: [mixin],
    data () {   
        return {
            createForm:{
                userName:'',
                jobNumber:'',
                originalWorkCenter:'',
                originalJobCategory:'',
                originalJobTitle:'',
                originalUserName:'',
                originalParentNumber:'',
                nowWorkCenter:'',
                nowJobCategory:'',
                nowJobTitle:'',
                nowUserName:'',
                nowParentNumber:'',
            },
            rules: {
              userName: [
                { required: true, message: '姓名不能为空', trigger: 'blur' }
              ],
              jobNumber: [
                { required: true, message: '工号不能为空', trigger: 'blur' }
              ],
              originalWorkCenter: [
                { required: true, message: '原工作中心不能为空', trigger: 'blur' }
              ],
              originalJobCategory: [
                { required: true, message: '原岗位类别不能为空', trigger: 'blur' }
              ],
              originalJobTitle: [
                { required: true, message: '原岗位名称不能为空', trigger: 'blur' }
              ],
              originalUserName: [
                { required: true, message: '原直接主管不能为空', trigger: 'blur' }
              ],
              originalParentNumber: [
                { required: true, message: '原直接主管工号不能为空', trigger: 'blur' }
              ],
              nowWorkCenter: [
                { required: true, message: '新工作中心不能为空', trigger: 'blur' }
              ],
              nowJobCategory: [
                { required: true, message: '新岗位类别不能为空', trigger: 'blur' }
              ],
              nowJobTitle: [
                { required: true, message: '新岗位名称不能为空', trigger: 'blur' }
              ],
              nowUserName: [
                { required: true, message: '新直接主管不能为空', trigger: 'blur' }
              ],
              nowParentNumber: [
                { required: true, message: '新直接主管工号不能为空', trigger: 'blur' }
              ],
            },
            action: uploadURL + `/back/user-knowledge-record/UserKnowledgeRecordEntryExcel`,
            fileList: [],
            httpHeader: {
          'Authorization': ''
      },
            userInfo:{},
            jobTitleList:[],
            tableInfo:[],           //岗前培训列表
            tableData:[],           //岗位培训列表
            currentPage1:0,
            total:0, 
            ferState:1,
            GQbool: true,
            GWbool: true,
            allBool: false,        // 全部禁用
            userList: [], 
            getUserList:[],            // 获取转岗人列表
            jobCategoryList: ['1线','1.5线','2线'], 
            dialogFormVisible: false,
            StartingList:[],       // 上岗人员列表
            startingName:'',
            printerName: '',
            printerNameList: [],
            rowSelect1:[],         // 选择列表
            printLoading: false,
            boolGWAL: true,
        }
    },
    computed: {
    },
    methods: {
        submitUpload() {
        //  this.httpHeader.Authorization = this.dealCookie(document.cookie)
         this.httpHeader.Authorization = this.$store.state.user.token,
         this.$refs.upload.submit()
         },
         // 上传成功
         handleSuccess(response){
          if(response.code == 1){
            this.fileList = []
            this.$message.success(response.msg)
          } else {
            this.$message.error(response.msg)
          }
            this.handleFilter()
        },
       async changeName(e){
        if(!e) return this.createForm.jobNumber = ''
        this.userList.forEach(item => {
            if(item.userName == e){
                this.$set(this.createForm, 'jobNumber', item.jobNumber)
            }
        })
        await this.getData()
      },
      changeName1(e){
        if(!e) return this.createForm.jobNumber = ''
        this.userList.forEach(item => {
            if(item.userName == e){
                this.$set(this.createForm, 'nowParentNumber', item.jobNumber)
            }
        })
      },
         // 获取个人信息
         async getuserList(e){  
            let query = {page:1,limit:9999} 
            console.log(e)
            this.userList = []
            if(e == 1){
                if(this.createForm.userName){
                    query.username = this.createForm.userName
                }
            }else if(e == 2){
                if(this.createForm.nowUserName){
                    query.username = this.createForm.nowUserName
                }
            }
            const {data} = await searchWorkers(query)
            this.userList = data.records
        },
        async handleCurrentChange(e){
            console.log(e)
            this.GQbool = true
            this.GWbool = true
            this.tableInfo = []
            this.createForm = Object.assign({},this.getUserList[e-1])
            this.ferState = Number(this.getUserList[e-1].state)
            console.log(this.ferState)
                let query = {
                page: 1,
                limit: 10000,
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber,
                trainingCategory: '岗位案例培训'
                }
                const res = await recordFind(query)
                this.tableInfo = res.data.list
                if(this.hasMoreThanThreeObjectsWithKeyFailing(this.tableInfo, 'evaluationResult','不合格')){
                    this.tableInfo = res.data.list
                }else if(this.ferState >= 3){
                    this.tableInfo = res.data.list
                }else if(this.ferState == 2){
                    this.boolGWAL = true
                    this.tableInfo = []
                }
        },
        // 点击岗位前完成培训
        skipTrain(){
            let query = []
            this.tableInfo.forEach(item =>{
                query.push({trainingCategory:item.trainingCategory,trainingContent:item.trainingContent,type:'晋级'})
            })
            this.$router.push({ path: '/knowledgeSkill/trainingResults', query: query})
        },
        // 点击培训按钮
        async trainingClick(){
            let query = {
                page:1,
                limit:10000,
                userKnowledgePostId: this.createForm.nowUserKnowledgePostId, 
                trainingCategory: '岗位案例培训'
            }
            const res = await programFind(query)
            const arr =res.data.list
            if(res.data.list.length){
                    this.ferState = 3
                    let objectMap = []
                    arr.forEach( item =>{
                        objectMap.push({
                            userName: this.createForm.userName, 
                            jobNumber: this.createForm.jobNumber,
                            workCenter: this.createForm.workCenter,
                            jobCategory: this.createForm.jobCategory,
                            jobTitle: this.createForm.jobTitle,
                            userKnowledgePostId:this.createForm.userKnowledgePostId,
                            trainingContent: item.trainingContent,    
                            trainingInstructor:item.userName,
                            trainingCategory:item.trainingCategory,
                            evaluationMode:item.evaluationMode,
                            trainingTime:item.plannedTrainingTimeDate,
                            contentType:item.contentType,
                            userKnowledgeTrainingProgramId: item.id,  // 培训计划id
                            type:2,  // 1.入职与培训2.晋级管理3.转岗管理4.关键工序管理
                        })
                        // await recordSave(query1)
                    })
                    // 批量添加 员工履历
                    const res = await recordSaveList({objectMap:objectMap})
                    await userKnowledgeRecordState({id:this.createForm.id,state:3})
                    setTimeout(async () =>{
                        let query = {
                            page:1,
                            limit:10000,
                            userName:this.createForm.userName,
                            jobNumber:this.createForm.jobNumber,
                            trainingCategory: '岗位案例培训'
                        }
                        const res = await recordFind(query)
                        this.tableInfo = res.data.list
                    },500)
            } else {
                return this.$message.error('没有培训计划列表！')
            }
        },
         // 获取岗位
        async getjobTitle(){
            let query = {page:1,  limit:10000}
            if(this.createForm.nowJobCategory){query.jobCategory = this.createForm.nowJobCategory}
            if(this.createForm.nowWorkCenter){query.workCenter = this.createForm.nowWorkCenter}
            const res = await knowledgeFind(query)
            this.jobTitleList = res.data.list
            if(!res.data.list.length) return this.$message.error('工作中心和岗位类别未查询到数据!')
    },
     // 岗位改变
     changeJobTitle(e){
      this.jobTitleList.forEach(item =>{
        if(item.id == e){
          this.createForm.nowJobCategory = item.jobCategory
          this.createForm.nowWorkCenter = item.workCenter
          this.createForm.nowUserKnowledgePostId = item.id
        }
    })
    },
        async getData(){
            if(!this.createForm.userName || !this.createForm.jobNumber) return this.$message.error('请填写姓名或工号!')
            let query ={
                page: 1,
                limit: 10,
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber
            }
            const res = await searchWorkers(query)
            // if(!res.data.records.lenght) return  
            this.userInfo = res.data.records[0]
            this.$set(this.createForm, 'originalWorkCenter', this.userInfo.departmentName)
            this.$set(this.createForm, 'originalParentNumber', this.userInfo.parentNumber)
            this.$set(this.createForm, 'originalUserName', this.userInfo.parentName)
            this.$set(this.createForm, 'originalJobCategory', this.userInfo.userKnowledgePost.jobCategory)
            this.$set(this.createForm, 'originalJobTitle', this.userInfo.userKnowledgePost.jobTitle)
            this.$set(this.createForm, 'originalUserKnowledgePostId', this.userInfo.userKnowledgePost.id)
        },
        // 新增提交
        submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submit()
          } else {
            return false;
          }
        });
      },
        async submit(){
            let query = {
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber,
                nowUserName: this.createForm.nowUserName,
                nowParentNumber: this.createForm.nowParentNumber,
                originalParentNumber: this.createForm.originalParentNumber,
                originalUserName: this.createForm.originalUserName,
                originalUserKnowledgePostId: this.createForm.originalUserKnowledgePostId,
                nowUserKnowledgePostId: this.createForm.nowUserKnowledgePostId,
            }
           const res = await transferSave(query)
           if(res.code == '500') return
           if(res.code != '1') return this.$message.error(res.msg)
           this.$message.success(res.msg)
           this.handleFilter()
        },
        async handleFilter(){
            let query = {
                page:1,
                limit:10000,
                type:'2,22,222',
                noState:'结束'
            }
            const res = await recordFind(query)
            console.log('res',res)
            this.getUserList = res.data.list
            this.total = this.getUserList.length
            if(this.getUserList.length){
              this.createForm = Object.assign({},this.getUserList[0])
              this.ferState = Number(this.getUserList[0].state)
              console.log(this.ferState)
                let query = {
                page: 1,
                limit: 10000,
                userName: this.createForm.userName,
                jobNumber: this.createForm.jobNumber,
                trainingCategory: '岗位案例培训'
                }
                const res = await recordFind(query)
                this.tableInfo = res.data.list
                if(this.hasMoreThanThreeObjectsWithKeyFailing(this.tableInfo, 'evaluationResult','不合格')){
                    this.tableInfo = res.data.list
                }else if(this.ferState >= 3){
                    this.tableInfo = res.data.list
                }else if(this.ferState == 2){
                    this.boolGWAL = true
                    this.tableInfo = []
                }
            }
        },
        hasMoreThanThreeObjectsWithKeyFailing(arr, key, passingValue) {  
            let failingCount = 0; // 用于计数不合格的对象数量  
            // 遍历数组中的每个对象  
            for (let i = 0; i < arr.length; i++) {  
                // 检查当前对象是否具有指定的键  
                if (arr[i].hasOwnProperty(key)) {  
                    // 如果该键的值不等于给定的合格值，则增加不合格计数  
                    if (arr[i][key] !== passingValue) {  
                        failingCount++;  
                        // 如果不合格的对象数量已经超过三条，则直接返回false
                        if (failingCount > 3) {  
                            return false;  
                        }  
                    }  
                }  
            }
            // 如果没有超过三条不合格的对象，则返回true  
            return failingCount < 3;  
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style lang="scss" scoped>
.app-container{
    margin: 10px;
}
/deep/ .el-table__header .el-table-column--selection .cell .el-checkbox:after {
  content: "全选";
  margin-left: 5px;
}
</style>
